package com;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Configurator {
	private String rootDirectory;
	private int portServer;
	private int numberThread;

	Configurator(String filePath) {
		parse(filePath);
	}

	private void parse(String filePath) {
		try {
			File XMLfile = new File(filePath);
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			Document doc = dBuilder.parse(XMLfile);
			doc.getDocumentElement().normalize();
			NodeList nList = doc.getElementsByTagName("customization");
			if ((nList != null) && (nList.getLength() == 1)) {
				Node node = nList.item(0);
				if (node.getNodeType() == Node.ELEMENT_NODE) {
					Element element = (Element) node;
					portServer = Integer.parseInt(getValue("port", element));
					numberThread = Integer.parseInt(getValue("numberthread",
							element));
					rootDirectory = getValue("rootdirectory", element);
				}
			}
		} catch (Exception t) {
			System.out.println("Can't read XMLfile");
		}
	}

	private static String getValue(String tag, Element element) {
		NodeList nodes;
		Node node = null;
		try {
			nodes = element.getElementsByTagName(tag).item(0).getChildNodes();
			node = (Node) nodes.item(0);
		} catch (Exception e) {
			System.out.println("File Config hasn't tag - " + tag + " ");
			System.exit(0);
		}
		return node.getNodeValue();
	}

	public String getRootDirectory() {
		return rootDirectory;
	}

	public int getPort() {
		return portServer;
	}

	public int getNumberThread() {
		return numberThread;
	}
}
